#include <Python.h>

void garbage_init(void){
	
	Py_Initialize();

	// 将当前路径添加到sys.path中
	PyObject *sys = PyImport_ImportModule("sys");
	PyObject *path = PyObject_GetAttrString(sys, "path");
	PyList_Append(path, PyUnicode_FromString("."));

}

void garbage_final(void){
	//释放所有引用的Python对象
	Py_Finalize();
}

char *garbageClassID(char *garbage)
{
	// 导入garbage模块
	PyObject *pModule = PyImport_ImportModule("garbage");
	if (!pModule)
	{
		PyErr_Print();
		printf("Error: failed to load nopara.py\n");
		goto FALIED_MODULE;
	}
	
	//获取garbageClass_ID函数对象
	PyObject *pFunc = PyObject_GetAttrString(pModule, "garbageClass_ID");
	if (!pFunc)
	{
		PyErr_Print();
		printf("Error: failed to load say_funny\n");
		goto FALIED_FUNC;
	}

	//调用garbageClass_ID函数并获取返回值
	PyObject *pValue = PyObject_CallObject(pFunc, NULL);
	if (!pValue)
	{
		PyErr_Print();
		printf("Error: function call failed\n");
		goto FALIED_VALUE;
	}

	char *result = NULL;	
	//将返回值转换为C类型
	if (!PyArg_Parse(pValue, "s", &result))
	{
		PyErr_Print();
		printf("Error: parse failed\n");
		goto FALIED_RESULT;
	}
	
	//打印返回值
	garbage = (char*)malloc(sizeof(char)*strlen(result)+1);
	memset(garbage, 0, strlen(result)+1);
	strncpy(garbage, result, strlen(result)+1);	
    // printf("pValue=%s\n", garbage);
	//释放所有引用的Python对象
FALIED_RESULT: // 因为调用失败后对应的PyObject对象是没有申请到空间的,所以失败了根本不需要去释放空间
	Py_DECREF(pValue);
FALIED_VALUE:
	Py_DECREF(pFunc);
FALIED_FUNC:
	Py_DECREF(pModule);
FALIED_MODULE:
	return garbage;
}
